﻿using CSRedis;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Redis.Controllers
{


    public static class RedisHelperDemo
    {
        private static readonly string ConnectionString = "127.0.0.1:6379,password=123456";
        // private static readonly string ConnectionString = "127.0.0.1:6379,password=123456";

        private static ConnectionMultiplexer redis;
        private static IDatabase db { get; set; }
        static RedisHelperDemo()
        {
            if (1 == 2)//哨兵模式
            {
                var csredis = new CSRedis.CSRedisClient("redis-master", new[] { "127.0.0.1:27000" });
                //string redisServerIP = "172.16.0.13,172.16.0.13"; //哨兵IP列表
                //string redisServerPort = "26379,26380";
                //List<string> connectionList = GetRedisConnectionList(redisServerIP, redisServerPort);
                //CSRedisClient csredis = new CSRedisClient(ConnectionString, connectionList.ToArray());

                RedisHelper.Initialization(csredis);//初始化
            }
            redis = ConnectionMultiplexer.Connect(ConnectionString);
            db = redis.GetDatabase();
        }

        public static bool SetValue(string key, string value, TimeSpan time)
        {
            return db.StringSet(key, value, time);
        }

        public static string GetValue(string key)
        {
            return db.StringGet(key);
        }
        public static bool DeleteKey(string key)
        {
            return db.KeyDelete(key);
        }


        public static async Task SetHasTable(RedisKey key, HashEntry[] entries)
        {
            await db.HashSetAsync(key, entries);
        }


        public static async Task<HashEntry[]> GetHasTable(RedisKey key)
        {
            return db.HashGetAll(key);
        }

        //List 是双向链表结构，LinkList，插入，删除快，读取慢, 不做叙述


        //异步向Set(集合)中添加键值对 Redis 中集合是通过哈希表实现的，所以添加，删除，查找的复杂度都是 O(1)。
        public static async Task<bool> SetAddAsync(RedisKey key, RedisValue value)
        {
            return await db.SetAddAsync(key, value);
        }

        // 异步获取对应键的所有成员,无序 Redis 中集合是通过哈希表实现的，所以添加，删除，查找的复杂度都是 O(1)。
        public static async Task<RedisValue[]> SetMembersAsync(RedisKey key)
        {
            return await db.SetMembersAsync(key);
        }
    }
}
